/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fleet.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.fleet.entity.*;
import com.jeeplus.modules.fleet.service.*;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;

/**
 * 车队费用Controller
 * @author 李超辉
 * @version 2017-11-24
 */
@Controller
@RequestMapping(value = "${adminPath}/fleet/motorcadeCost")
public class MotorcadeCostController extends BaseController {

	@Autowired
	private MotorcadeCostService motorcadeCostService;
	@Autowired
	private MaintainCostService maintainCostService;
	@Autowired
	private RefuelingChargeService refuelingChargeService;
	@Autowired
	private DitchCostService ditchCostService;
	@Autowired
	private PutupCostService putupCostService;
	@Autowired
	private OtherExpensesService otherExpensesService;
	@Autowired
	private TyreCostService tyreCostService;
	@Autowired
	private ProtectCostService protectCostService;
	@Autowired
	private LossCostService lossCostService;
	@Autowired
	private FineCostService fineCostService;
	@Autowired
	private MaiCostService maiCostService;
	
	@ModelAttribute
	public MotorcadeCost get(@RequestParam(required=false) String id) {
		MotorcadeCost entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = motorcadeCostService.get(id);
		}
		if (entity == null){
			entity = new MotorcadeCost();
		}
		return entity;
	}
	
	/**
	 * 车队费用列表页面
	 */
	@RequiresPermissions("fleet:motorcadeCost:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/fleet/motorcadeCostList";
	}
	
		/**
	 * 车队费用列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fleet:motorcadeCost:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(MotorcadeCost motorcadeCost, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			motorcadeCost.setProjectName(pro);}
		Page<MotorcadeCost> page = motorcadeCostService.findPage(new Page<MotorcadeCost>(request, response), motorcadeCost);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑车队费用表单页面
	 */
	@RequiresPermissions(value={"fleet:motorcadeCost:view","fleet:motorcadeCost:add","fleet:motorcadeCost:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(MotorcadeCost motorcadeCost, Model model) {
		if(motorcadeCost.getId()!=null){
		if(motorcadeCost.getDisbursementType().equals("维修费")){
            model.addAttribute("maintainCost",maintainCostService.get(motorcadeCost.getCostNumber()));
		}
		if(motorcadeCost.getDisbursementType().equals("加油费")){
			model.addAttribute("refuelingCharge",refuelingChargeService.get(motorcadeCost.getCostNumber()));
		}
			if(motorcadeCost.getDisbursementType().equals("轮胎费")){
				model.addAttribute("tyreCost",tyreCostService.get(motorcadeCost.getCostNumber()));
			}
			if(motorcadeCost.getDisbursementType().equals("防护费")){
				model.addAttribute("protectCost",protectCostService.get(motorcadeCost.getCostNumber()));
			}
			if(motorcadeCost.getDisbursementType().equals("产品损耗")){
				model.addAttribute("lossCost",lossCostService.get(motorcadeCost.getCostNumber()));
			}
		if(motorcadeCost.getDisbursementType().equals("路桥费")){
			model.addAttribute("ditchCost",ditchCostService.get(motorcadeCost.getCostNumber()));
		}
		if(motorcadeCost.getDisbursementType().equals("住宿费")){
			model.addAttribute("putupCost",putupCostService.get(motorcadeCost.getCostNumber()));
		}
		if(motorcadeCost.getDisbursementType().equals("其它费用")){
			model.addAttribute("otherExpenses",otherExpensesService.get(motorcadeCost.getCostNumber()));
		}
			if(motorcadeCost.getDisbursementType().equals("日常保养")){
				model.addAttribute("maiCost",maiCostService.get(motorcadeCost.getCostNumber()));
			}
			if(motorcadeCost.getDisbursementType().equals("罚款及其它")){
				model.addAttribute("fineCost",fineCostService.get(motorcadeCost.getCostNumber()));
			}


		}
		model.addAttribute("motorcadeCost", motorcadeCost);
		return "modules/fleet/motorcadeCostForm";
	}

	/**
	 * 保存车队费用
	 */
	@ResponseBody
	@RequiresPermissions(value={"fleet:motorcadeCost:add","fleet:motorcadeCost:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(MotorcadeCost m,HttpServletRequest req, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, m)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		if(m.getIsNewRecord()) {
			String maintainCost = req.getParameter("maintainCost");
			String refuelingCharge = req.getParameter("refuelingCharge");
			String ditchCost = req.getParameter("ditchCost");
			String putupCost = req.getParameter("putupCost");
			String tyreCost = req.getParameter("tyreCost");
			String lossCost  = req.getParameter("lossCost");
			String protectCost = req.getParameter("protectCost");
			String otherExpenses = req.getParameter("otherExpenses");
			String maiCost  = req.getParameter("maiCost");
			String fineCost = req.getParameter("fineCost");
			if (lossCost != null && lossCost != "") {
				String[] ids = lossCost.split(",");
				for (String id : ids) {
					MotorcadeCost motorcadeCost = new MotorcadeCost();
					motorcadeCost.setCarRegistration(m.getCarRegistration());
					motorcadeCost.setDriver(m.getDriver());
					motorcadeCost.setVehicleInformation(m.getVehicleInformation());
					motorcadeCost.setDate(m.getDate());
					motorcadeCost.setCostNumber(id);
					motorcadeCost.setCost(lossCostService.get(id).getZje() + "");
					motorcadeCost.setDisbursementType("产品损耗");
					motorcadeCost.setProjectName(UserUtils.getUseroffice());
					motorcadeCostService.save(motorcadeCost);//新建保存
				}

			}
			if (protectCost != null && protectCost != "") {
				String[] ids = protectCost.split(",");
				for (String id : ids) {
					MotorcadeCost motorcadeCost = new MotorcadeCost();
					motorcadeCost.setCarRegistration(m.getCarRegistration());
					motorcadeCost.setDriver(m.getDriver());
					motorcadeCost.setVehicleInformation(m.getVehicleInformation());
					motorcadeCost.setDate(m.getDate());
					motorcadeCost.setCostNumber(id);
					motorcadeCost.setCost(protectCostService.get(id).getMo() + "");
					motorcadeCost.setDisbursementType("防护费");
					motorcadeCost.setProjectName(UserUtils.getUseroffice());
					motorcadeCostService.save(motorcadeCost);//新建保存
				}

			}
			if (tyreCost != null && tyreCost != "") {
				String[] ids = tyreCost.split(",");
				for (String id : ids) {
					MotorcadeCost motorcadeCost = new MotorcadeCost();
					motorcadeCost.setCarRegistration(m.getCarRegistration());
					motorcadeCost.setDriver(m.getDriver());
					motorcadeCost.setVehicleInformation(m.getVehicleInformation());
					motorcadeCost.setDate(m.getDate());
					motorcadeCost.setCostNumber(id);
					motorcadeCost.setCost(tyreCostService.get(id).getJe() + "");
					motorcadeCost.setDisbursementType("轮胎费");
					motorcadeCost.setProjectName(UserUtils.getUseroffice());
					motorcadeCostService.save(motorcadeCost);//新建保存
				}

			}
			if (maintainCost != null && maintainCost != "") {
				String[] ids = maintainCost.split(",");
				for (String id : ids) {
					MotorcadeCost motorcadeCost = new MotorcadeCost();
					motorcadeCost.setCarRegistration(m.getCarRegistration());
					motorcadeCost.setDriver(m.getDriver());
					motorcadeCost.setVehicleInformation(m.getVehicleInformation());
					motorcadeCost.setDate(m.getDate());
					motorcadeCost.setCostNumber(id);
					motorcadeCost.setCost(maintainCostService.get(id).getMoney() + "");
					motorcadeCost.setDisbursementType("维修费");
					motorcadeCost.setProjectName(UserUtils.getUseroffice());
					motorcadeCostService.save(motorcadeCost);//新建保存
				}

			}
			if (refuelingCharge != null && refuelingCharge != "") {
				String[] ids = refuelingCharge.split(",");
				for (String id : ids) {
					MotorcadeCost motorcadeCost = new MotorcadeCost();
					motorcadeCost.setCarRegistration(m.getCarRegistration());
					motorcadeCost.setDriver(m.getDriver());
					motorcadeCost.setVehicleInformation(m.getVehicleInformation());
					motorcadeCost.setDate(m.getDate());
					motorcadeCost.setCostNumber(id);
					motorcadeCost.setCost(refuelingChargeService.get(id).getMoney() + "");
					motorcadeCost.setDisbursementType("加油费");
					motorcadeCost.setProjectName(UserUtils.getUseroffice());
					motorcadeCostService.save(motorcadeCost);//新建保存}
				}}
				if (ditchCost != null && ditchCost != "") {
					String[] ids = ditchCost.split(",");
					for (String id : ids) {

					MotorcadeCost motorcadeCost = new MotorcadeCost();
					motorcadeCost.setCarRegistration(m.getCarRegistration());
					motorcadeCost.setDriver(m.getDriver());
					motorcadeCost.setVehicleInformation(m.getVehicleInformation());
					motorcadeCost.setDate(m.getDate());
					motorcadeCost.setCostNumber(id);
					motorcadeCost.setCost(ditchCostService.get(id).getMoney() + "");
					motorcadeCost.setDisbursementType("路桥费");
					motorcadeCost.setProjectName(UserUtils.getUseroffice());
					motorcadeCostService.save(motorcadeCost);//新建保存
				}}
				if (otherExpenses != null && otherExpenses != "") {
					String[] ids = otherExpenses.split(",");
					for (String id : ids) {
					MotorcadeCost motorcadeCost = new MotorcadeCost();
					motorcadeCost.setCarRegistration(m.getCarRegistration());
					motorcadeCost.setDriver(m.getDriver());
					motorcadeCost.setVehicleInformation(m.getVehicleInformation());
					motorcadeCost.setDate(m.getDate());
					motorcadeCost.setCostNumber(id);
					motorcadeCost.setCost(otherExpensesService.get(id).getMoney() + "");
					motorcadeCost.setDisbursementType("其它费用");
					motorcadeCost.setProjectName(UserUtils.getUseroffice());
					motorcadeCostService.save(motorcadeCost);//新建保存
				}}
				if (putupCost != null && putupCost != "") {
					String[] ids = putupCost.split(",");
					for (String id : ids) {
					MotorcadeCost motorcadeCost = new MotorcadeCost();
					motorcadeCost.setCarRegistration(m.getCarRegistration());
					motorcadeCost.setDriver(m.getDriver());
					motorcadeCost.setVehicleInformation(m.getVehicleInformation());
					motorcadeCost.setDate(m.getDate());
					motorcadeCost.setCostNumber(id);
					motorcadeCost.setCost(putupCostService.get(id).getMoney() + "");
					motorcadeCost.setDisbursementType("住宿费");
					motorcadeCost.setProjectName(UserUtils.getUseroffice());
					motorcadeCostService.save(motorcadeCost);//新建保存
				}}
			if (maiCost != null && maiCost != "") {
				String[] ids = maiCost.split(",");
				for (String id : ids) {
					MotorcadeCost motorcadeCost = new MotorcadeCost();
					motorcadeCost.setCarRegistration(m.getCarRegistration());
					motorcadeCost.setDriver(m.getDriver());
					motorcadeCost.setVehicleInformation(m.getVehicleInformation());
					motorcadeCost.setDate(m.getDate());
					motorcadeCost.setCostNumber(id);
					motorcadeCost.setCost(maiCostService.get(id).getByje() + "");
					motorcadeCost.setDisbursementType("日常保养");
					motorcadeCost.setProjectName(UserUtils.getUseroffice());
					motorcadeCostService.save(motorcadeCost);//新建保存
				}}
			if (fineCost != null && fineCost != "") {
				String[] ids = fineCost.split(",");
				for (String id : ids) {
					MotorcadeCost motorcadeCost = new MotorcadeCost();
					motorcadeCost.setCarRegistration(m.getCarRegistration());
					motorcadeCost.setDriver(m.getDriver());
					motorcadeCost.setVehicleInformation(m.getVehicleInformation());
					motorcadeCost.setDate(m.getDate());
					motorcadeCost.setCostNumber(id);
					motorcadeCost.setCost(fineCostService.get(id).getFkje() + "");
					motorcadeCost.setDisbursementType("罚款及其它");
					motorcadeCost.setProjectName(UserUtils.getUseroffice());
					motorcadeCostService.save(motorcadeCost);//新建保存
				}}

			} else {
				motorcadeCostService.save(m);//编辑保存
			}


		j.setSuccess(true);
		j.setMsg("保存车队费用成功");
		return j;
	}
	
	/**
	 * 删除车队费用
	 */
	@ResponseBody
	@RequiresPermissions("fleet:motorcadeCost:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(MotorcadeCost motorcadeCost, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
        del(motorcadeCost);
		motorcadeCostService.delete(motorcadeCost);
		j.setMsg("删除车队费用成功");
		return j;
	}

	public  void del(MotorcadeCost motorcadeCost){
		String id=motorcadeCost.getCostNumber();
		if(motorcadeCost.getDisbursementType().equals("维修费")){
			maintainCostService.delete(maintainCostService.get(id));
		}else if(motorcadeCost.getDisbursementType().equals("加油费")){
			refuelingChargeService.delete(refuelingChargeService.get(id));
		}else if(motorcadeCost.getDisbursementType().equals("路桥费")){
			ditchCostService.delete(ditchCostService.get(id));
		}else if(motorcadeCost.getDisbursementType().equals("住宿费")){
			putupCostService.delete(putupCostService.get(id));
		} else if(motorcadeCost.getDisbursementType().equals("其它费用")){
			otherExpensesService.delete(otherExpensesService.get(id));
		}
	 else if(motorcadeCost.getDisbursementType().equals("罚款及其它")){
		fineCostService.delete(fineCostService.get(id));
	} else if(motorcadeCost.getDisbursementType().equals("日常保养")){
		maiCostService.delete(maiCostService.get(id));
	} else if(motorcadeCost.getDisbursementType().equals("防护费")){
			protectCostService.delete(protectCostService.get(id));
	} else if(motorcadeCost.getDisbursementType().equals("产品损耗")){
			lossCostService.delete(lossCostService.get(id));
	}else if(motorcadeCost.getDisbursementType().equals("轮胎费")){
			tyreCostService.delete(tyreCostService.get(id));
		}


	}

	/**
	 * 批量删除车队费用
	 */
	@ResponseBody
	@RequiresPermissions("fleet:motorcadeCost:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			del(motorcadeCostService.get(id));
			motorcadeCostService.delete(motorcadeCostService.get(id));
		}
		j.setMsg("删除车队费用成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fleet:motorcadeCost:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(MotorcadeCost motorcadeCost, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "车队费用"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<MotorcadeCost> page = motorcadeCostService.findPage(new Page<MotorcadeCost>(request, response, -1), motorcadeCost);
    		new ExportExcel("车队费用", MotorcadeCost.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出车队费用记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fleet:motorcadeCost:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<MotorcadeCost> list = ei.getDataList(MotorcadeCost.class);
			for (MotorcadeCost motorcadeCost : list){
				try{
					motorcadeCostService.save(motorcadeCost);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条车队费用记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条车队费用记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入车队费用失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fleet/motorcadeCost/?repage";
    }
	
	/**
	 * 下载导入车队费用数据模板
	 */
	@RequiresPermissions("fleet:motorcadeCost:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "车队费用数据导入模板.xlsx";
    		List<MotorcadeCost> list = Lists.newArrayList(); 
    		new ExportExcel("车队费用数据", MotorcadeCost.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fleet/motorcadeCost/?repage";
    }

}